<?php


namespace app\controller\depot;
require_once __DIR__.'/../../common/AuthController.php';
use app\common\AuthController;

/**
 * 仓库库存
 */
class Stock extends AuthController
{   


    /**
     * 初始化操作
     */
    public function init()
    {

    }
	

    /**
     * 获取仓库库存列表
     */
	public function api_depot_stock_getList($msg)
    {   
        global $db;
        $info = [
            'page' =>  isset($msg['data']['page'])?$msg['data']['page']:1,
            'rows' => isset($msg['data']['rows'])?$msg['data']['rows']:15,
            'id' => isset($msg['data']['id'])?$msg['data']['id']:'',
            'depot_name' => isset($msg['data']['depot_name'])?$msg['data']['depot_name']:'',
            'goods_code' => isset($msg['data']['goods_code'])?$msg['data']['goods_code']:'',
            'goods_name' => isset($msg['data']['goods_name'])?$msg['data']['goods_name']:'',
        ];
        $limit = ($info['page']-1)*$info['rows'].','.$info['rows'];
        $where = "is_delete = 0";
        if(!empty($info['id'])){
            $where .= " AND id =".$info['id'];
        }
        if(!empty($info['depot_name'])){
            $where .= " AND depot_name LIKE '%".$info['depot_name']."%'";
        }
        if(!empty($info['goods_code'])){
            $where .= " AND goods_code LIKE '%".$info['goods_code']."%'";
        }
        if(!empty($info['goods_name'])){
            $where .= " AND goods_name LIKE '%".$info['goods_name']."%'";
        }
		$list = $db->query("select * from depot_stock where ".$where ." order by id  desc limit ".$limit); 
        $count =  $db->query("SELECT count(*) as count from depot_stock WHERE ".$where);
        return $this->outMessage(10000,'获取成功',$list,'success',$count[0]['count']);
	}



    /**
     * 出入库统计表
     */
    public function api_depot_stock_turnoverStatistics($msg)
    {   
        global $db;
        $info = [
            'page' =>  isset($msg['data']['page'])?$msg['data']['page']:1,
            'rows' => isset($msg['data']['rows'])?$msg['data']['rows']:15,
            'time' => isset($msg['data']['time'])?$msg['data']['time']:'',
        ];
        $start_time = date('Y-m-d',time()).' 00:00:00';
        if(!empty($info['time'])){
            $start_time = $info['time'].' 00:00:00';
        }
        $limit = ($info['page']-1)*$info['rows'].','.$info['rows'];
        $where = "a.is_delete = 0";
        if(!empty($info['time'])){
            $where .= " AND a.create_time >".$start_time;
        }
        // $list = $db->query("SELECT a.depot_id,a.depot_name,a.contact_name,sum(b.number) as enter_number,b.price,a.create_time FROM depot_flow_log as a left join depot_goods as b on a.order_no = b.order_no WHERE ".$where ." AND a.type = 1 GROUP BY a.depot_id order by a.create_time  desc limit ".$limit); 
        $list = $db->query("SELECT a.depot_id,a.depot_name,a.contact_name,sum(b.number) as enter_number,b.price,a.create_time FROM depot_flow_log as a left join depot_goods as b on a.order_no = b.order_no WHERE ".$where ." GROUP BY a.depot_id order by a.create_time  desc limit ".$limit); 
        if(!empty($list)){
            foreach ($list as $k => $v) {
                // $data = $db->query("SELECT sum(b.number) as number,b.price FROM depot_flow_log as a left join depot_goods as b on a.order_no = b.order_no WHERE ".$where ." AND a.type = 2 AND a.depot_id = ".$v['depot_id']." GROUP BY a.depot_id");
                $data = $db->query("SELECT sum(b.number) as number,b.price FROM depot_flow_log as a left join depot_goods as b on a.order_no = b.order_no WHERE ".$where ." AND a.depot_id = ".$v['depot_id']." GROUP BY a.depot_id");
                if(!empty($data)){
                    $list[$k]['come_number'] = $data[0]['number'];
                    $list[$k]['sum_come_money'] = $data[0]['number']*$data[0]['price'];
                }else{
                    $list[$k]['come_number'] = 0;
                    $list[$k]['sum_come_money'] = 0;
                }
                $list[$k]['sum_enter_money'] = $v['enter_number']*$v['price'];
                $list[$k]['year'] = substr($v['create_time'], 0,4);
                $list[$k]['month'] = substr($v['create_time'], 5,2);
                unset($list[$k]['create_time'],$list[$k]['depot_id'],$list[$k]['price']);
            }
        }
        $count =  $db->query("SELECT count(*) as count FROM depot_flow_log as a left join depot_goods as b on a.order_no = b.order_no WHERE ".$where ." GROUP BY a.depot_id ");
        return $this->outMessage(10000,'获取成功',$list,'success',$count[0]['count']);
    }



    /**
     * 进出明细
     */
    public function api_depot_stock_flowLog($msg)
    {
        global $db;
        $info = [
            'page' =>  isset($msg['data']['page'])?$msg['data']['page']:1,
            'rows' => isset($msg['data']['rows'])?$msg['data']['rows']:15,
            'goods_name' => isset($msg['data']['goods_name'])?$msg['data']['goods_name']:'',
            'depot_name' => isset($msg['data']['depot_name'])?$msg['data']['depot_name']:'',
            'type' => isset($msg['data']['type'])?$msg['data']['type']:'',
            'status' => isset($msg['data']['status'])?$msg['data']['status']:'',
        ];
        $limit = ($info['page']-1)*$info['rows'].','.$info['rows'];
        $where = "a.is_delete = 0";
        if(!empty($info['type'])){
            $where .= " AND b.type =".$info['type'];
        }
        if(!empty($info['status'])){
            $where .= " AND b.status =".$info['status'];
        }
        if(!empty($info['depot_name'])){
            $where .= " AND b.depot_name LIKE '%".$info['depot_name']."%'";
        }
        if(!empty($info['goods_name'])){
            $where .= " AND a.goods_name LIKE '%".$info['goods_name']."%'";
        }
        $list = $db->query("SELECT a.goods_name,a.goods_code,a.brand_name,a.category_name,a.attribute,a.units_name,a.number,a.price,a.create_time,b.order_no,b.depot_name,b.contact_name,b.type,b.status,b.check_nickname FROM depot_goods as a left join depot_flow_log as b on a.order_no = b.order_no WHERE ".$where ." order by a.create_time  desc limit ".$limit); 
        $count =  $db->query("SELECT count(*) as count FROM depot_goods as a left join depot_flow_log as b on a.order_no = b.order_no WHERE ".$where);
        return $this->outMessage(10000,'获取成功',$list,'success',$count[0]['count']);
    }



    /**
     * 缺货列表
     */
    public function api_depot_stock_lackList($msg)
    {
        global $db;
        $info = [
            'page' =>  isset($msg['data']['page'])?$msg['data']['page']:1,
            'rows' => isset($msg['data']['rows'])?$msg['data']['rows']:15,
            'goods_name' => isset($msg['data']['goods_name'])?$msg['data']['goods_name']:'',
            'name' => isset($msg['data']['name'])?$msg['data']['name']:'',
            'itoc_name' => isset($msg['data']['itoc_name'])?$msg['data']['itoc_name']:'',
            'supplier_name' => isset($msg['data']['supplier_name'])?$msg['data']['supplier_name']:'',
        ];
        $limit = ($info['page']-1)*$info['rows'].','.$info['rows'];
        $where = "a.is_delete = 0 AND a.stock < a.min_stock_alarm";
        if(!empty($info['name'])){
            $where .= " AND b.name LIKE '%".$info['name']."%'";
        }
        if(!empty($info['goods_name'])){
            $where .= " AND a.goods_name LIKE '%".$info['goods_name']."%'";
        }
        if(!empty($info['supplier_name'])){
            $where .= " AND a.supplier_name LIKE '%".$info['supplier_name']."%'";
        }
        if(!empty($info['itoc_name'])){
            $where .= " AND b.itoc_name LIKE '%".$info['itoc_name']."%'";
        }
        $list = $db->query("SELECT a.id,a.goods_name,a.goods_code,a.brand_name,a.category_name,a.attribute,a.units_name,a.stock,a.min_stock_alarm,a.supplier_name,b.name,b.itoc_name,b.region_name FROM depot_stock as a left join depot as b on a.depot_id = b.id WHERE ".$where ." order by a.create_time  desc limit ".$limit); 
        $count =  $db->query("SELECT count(*) as count FROM depot_stock as a left join depot as b on a.depot_id = b.id WHERE ".$where);
        return $this->outMessage(10000,'获取成功',$list,'success',$count[0]['count']);
    }



    /**
     * 获取该商品库存数量
     */
    public function api_depot_stock_stockNumber($msg){
        global $db;
        $info = [
            'depot_id' =>  isset($msg['data']['depot_id'])?$msg['data']['depot_id']:'',
            'goods_id' => isset($msg['data']['goods_id'])?$msg['data']['goods_id']:'',
        ];
        foreach ($info as $v) {
            if(empty($v)){
                return $this->outMessage(-1,'参数不能为空');
            }
        }
        $data = $db->query("SELECT goods_id,stock FROM depot_stock WHERE depot_id = ".$info['depot_id']." AND goods_id in (".$info['goods_id'].")");
        // if(empty($data)){
        //     return $this->outMessage(-1,'获取失败,该仓库没有这个商品.');
        // }
        return $this->outMessage(10000,'获取成功',$data);
    }



    /**
     * 备货完成
     */
    public function api_depot_stock_stockUp($msg)
    {
        $info = [
            'order_no' =>  isset($msg['data']['order_no'])?$msg['data']['order_no']:'',
            'remark' => isset($msg['data']['remark'])?$msg['data']['remark']:'',
        ];
        $goods_list = isset($msg['data']['goods_list'])?$msg['data']['goods_list']:'';
        if(empty($info['order_no'])){
            return $this->outMessage(-1,'编号不能为空');
        }
        if(!empty($info['remark'])){
            if(!$this->validate->checkName($info['remark'],2,100)){
                return $this->outMessage(-1,'请输入正确的备注');
            }
        } 
        if(!is_array($goods_list) || empty($goods_list)){
            return $this->outMessage(-1,'备货信息不能为空');
        }
        $data = [
            'status' =>2,
            'stock_up_explain'=>$info['remark'],
            'stock_up_time' => date('Y-m-d H:i:s',time())
        ];
        $res = $this->table->update('take_cargo',['order_no'=>$info['order_no']],$data);
        if(!$res){
            return $this->outMessage(-1,'提交失败');
        }
        foreach ($goods_list as $v) {
            $res = $this->table->update('take_cargo_goods',['order_no'=>$info['order_no'],'goods_id'=>$v['goods_id']],['reality_number'=>$v['reality_number']]);
            if(!$res){
                return $this->outMessage(-1,'提交失败');
            }
        }
        return $this->outMessage(10000,'提交成功');
    }



    /**
     * 出库完成
     */
    public function api_depot_stock_takeSuccess($msg)
    {
        $info = [
            'id' =>  isset($msg['data']['id'])?$msg['data']['id']:'',
            'consignee' => isset($msg['data']['consignee'])?$msg['data']['consignee']:''
        ];
        if(empty($info['id'])){
            return $this->outMessage(-1,'id不能为空');
        }
        if(empty($info['consignee'])){
            return $this->outMessage(-1,'提货人不能为空');
        }
        $this->admin_id = 1;
        $admin = $this->table->find('admin',['id'=>$this->admin_id]); 
        $data = [
            'status' => 3,
            'take_principal_id' =>$this->admin_id,
            'take_principal_nickname'=>$admin['nickname'],
            'consignee' => $info['consignee'],
            'take_time' => date('Y-m-d H:i:s',time()),
            'update_time' => date('Y-m-d H:i:s',time())
        ];
        $res = $this->table->update('take_cargo',['id'=>$info['id']],$data);
        if(!$res){
            return $this->outMessage(-1,'提交失败');
        }
        return $this->outMessage(10000,'提交成功');
    }



    /**
     * 入库单列表
     */
    public function api_depot_stock_purchaseList($msg)
    {
        global $db;
        $info = [
            'page' =>  isset($msg['data']['page'])?$msg['data']['page']:1,
            'rows' => isset($msg['data']['rows'])?$msg['data']['rows']:15,
            'id' => isset($msg['data']['id'])?$msg['data']['id']:'',
            'status' => isset($msg['data']['status'])?$msg['data']['status']:'',
            'depot_name' => isset($msg['data']['depot_name'])?$msg['data']['depot_name']:'',
            'itoc_name' => isset($msg['data']['itoc_name'])?$msg['data']['itoc_name']:'',
            'supplier_name' => isset($msg['data']['supplier_name'])?$msg['data']['supplier_name']:'',
            'order_no' => isset($msg['data']['order_no'])?$msg['data']['order_no']:'',
        ];
        $limit = ($info['page']-1)*$info['rows'].','.$info['rows'];
        $where = "is_delete = 0";
        if(!empty($info['id'])){
            $where .= " AND id =".$info['id'];
        }
        if(!empty($info['status'])){
            $where .= " AND status =".$info['status'];
        }
        if(!empty($info['depot_name'])){
            $where .= " AND depot_name LIKE '%".$info['depot_name']."%'";
        }
        if(!empty($info['itoc_name'])){
            $where .= " AND itoc_name LIKE '%".$info['itoc_name']."%'";
        }
        if(!empty($info['supplier_name'])){
            $where .= " AND supplier_name LIKE '%".$info['supplier_name']."%'";
        }
        if(!empty($info['order_no'])){
            $where .= " AND order_no LIKE '%".$info['order_no']."%'";
        }
        $list = $db->query("select * from depot_purchase where ".$where ." order by id  desc limit ".$limit); 
        $count =  $db->query("SELECT count(*) as count from depot_purchase WHERE ".$where);
        return $this->outMessage(10000,'获取成功',$list,'success',$count[0]['count']);
    }



    /**
     * 入库单详情
     */
    public function api_depot_stock_purchaseDetails($msg)
    {
        $order_no = isset($msg['data']['order_no'])?$msg['data']['order_no']:'';
        $list = $this->table->select('depot_goods',['order_no'=>$order_no]);
        return $this->outMessage(10000,'获取成功',$list);
    }



    /**
     * 入库操作
     */
    public function api_depot_stock_purchaseSuccess($msg)
    {
        $order_no = isset($msg['data']['order_no'])?$msg['data']['order_no']:'';
        $goods_list = isset($msg['data']['goods_list'])?$msg['data']['goods_list']:'';
        if(empty($order_no)){
            return $this->outMessage(-1,'订单编号不能为空');
        }
        if(!is_array($goods_list) || empty($goods_list)){
            return $this->outMessage(-1,'商品信息不能为空');
        }
        $order = $this->table->find('goods_request_addr',['order_no'=>$order_no]);
        if($order['status'] != 4){
            return $this->outMessage(-1,'该订单暂未发货');
        }
        $actual_number = 0;
        foreach ($goods_list as $v) {
            //入库单
            $res = $this->table->update('depot_goods',['order_no'=>$order_no,'goods_id'=>$v['goods_id']],['actual_number'=>$v['actual_number']]);
            //采购单
            $res = $this->table->update('goods_request_list',['order_no'=>$order_no,'goods_id'=>$v['goods_id']],['actual_number'=>$v['actual_number']]);
            //申请单
            $res = $this->table->update('goods_request_list',['order_no'=>$order['link_order_no'],'goods_id'=>$v['goods_id']],['actual_number'=>$v['actual_number']]);
            $actual_number += $v['actual_number'];
        }
        $this->admin_id = 1;
        $admin = $this->table->find('admin',['id'=>$this->admin_id]);
        $data = [
            'actual_number' => $actual_number,
            'status' => 3,
            'access_principal_id' => $this->admin_id,
            'access_nickname' => $admin['nickname'],
            'access_time' => date('Y-m-d H:i:s',time())
        ];
        //入库单
        $res = $this->table->update('depot_purchase',['order_no'=>$order_no],$data);
        if(!$res){
            return $this->outMessage(-1,'提交失败');
        }
        //采购单
        $res = $this->table->update('goods_request_addr',['order_no'=>$order_no],['actual_number'=>$actual_number,'status'=>5]);
        if(!$res){
            return $this->outMessage(-1,'提交失败');
        }
        //申请单
        $res = $this->table->update('goods_request_addr',['order_no'=>$order['link_order_no']],['actual_number'=>$actual_number,'status'=>5]);
        if(!$res){
            return $this->outMessage(-1,'提交失败');
        }
        //生成进出明细
        $info = $this->table->find('depot_purchase',['order_no'=>$order_no]);
        $flow_data = [
            'order_no' => $this->common->createOutTradeNo('F'),
            'depot_id' => $info['depot_id'],
            'depot_name' => $info['depot_name'],
            'contact_id' => $info['supplier_id'],
            'contact_name' => $info['supplier_name'],
            'sum_number' => $info['actual_number'],
            'type' => 2,
            'status' => 3,
            'check_admin_id' => $info['access_principal_id'],
            'check_nickname' => $info['access_nickname'],
            'check_time' => date('Y-m-d H:i:s',time()),
            'remark' => '采购入库',
            'create_time' => date('Y-m-d H:i:s',time()),
            'goods_list' => []
        ];
        //进出明细商品详情
        foreach ($goods_list as $k => $v) {
            $goods = $this->table->find('goods',['id'=>$v['goods_id']]);
            $goods_data = [
                'order_no' => $flow_data['order_no'],
                'goods_id' => $v['goods_id'],
                'goods_code' => $goods['code'],
                'goods_name' => $goods['name'],
                'category_id' => $goods['category_id_2'],
                'category_name' => $goods['category_name_2'],
                'brand_id' => $goods['brand_id'],
                'brand_name' => $goods['brand_name'],
                'attribute' => $goods['attribute'],
                'units_name' => $goods['units_name'],
                'number' => $v['actual_number'],
                'price' => $goods['buy_price'],
                'create_time' => date('Y-m-d H:i:s',time())
            ];
            array_push($flow_data['goods_list'],$goods_data);
        }
        $res = $this->createFlow($flow_data);
        if(!$res){
            return $this->outMessage(-1,'提交失败');
        }
        return $this->outMessage(10000,'提交成功');
    }



    /**
     * 创建进出明细
     */
    protected function createFlow($data)
    {
        if(!is_array($data) || empty($data)){
            return false;
        }
        if(!is_array($data['goods_list']) || empty($data['goods_list'])){
            return false;
        }
        foreach ($data['goods_list'] as $k => $v) {
            $res = $this->table->insert('depot_goods',$v);
            if(!$res){
                return false;
            }
            $info = $this->table->find('depot_stock',['depot_id'=> $data['depot_id'],'goods_id'=>$v['goods_id']]);
            //如果库存里面不存在该商品就去创建一个
            if(empty($info)){
                $goods = $this->table->find('goods',['id'=>$v['goods_id']]);
                $stock_data = [
                    'depot_id' => $data['depot_id'],
                    'depot_name' => $data['depot_name'],
                    'goods_id' => $v['goods_id'],
                    'goods_code' => $goods['code'],
                    'goods_name' => $goods['name'],
                    'goods_pic' => $goods['main_pic'],
                    'brand_id' => $goods['brand_id'],
                    'brand_name' => $goods['brand_name'],
                    'category_id' => $goods['category_id_2'],
                    'category_name' => $goods['category_name_2'],
                    'supplier_id' => $goods['supplier_id'],
                    'supplier_name' => $goods['supplier_name'],
                    'attribute' => $goods['attribute'],
                    'units_id' => $goods['units_id'],
                    'units_name' => $goods['units_name'],
                    'price' => $goods['buy_price'],
                    'create_time' => date('Y-m-d H:i:s',time())
                ];
                $this->table->insert('depot_stock',$stock_data);
            }
            $stock_list[$k]['depot_id'] = $data['depot_id'];
            $stock_list[$k]['goods_id'] = $v['goods_id'];
            $stock_list[$k]['number'] = $v['number'];
        }
        unset($data['goods_list']);
        $res = $this->table->insert('depot_flow_log',$data);
        if(!$res){
            return false;
        }
        //对库存进行修改
        $this->stockEdit($stock_list);
        return true;
    }




    /**
     * 对库存进行修改
     */
    protected function stockEdit($data,$type = 1){
        global $db;
        if(!is_array($data) || empty($data)){
            return false;
        }
        foreach ($data as $v) {
            $info = $this->table->find('depot_stock',['depot_id'=>$v['depot_id'],'goods_id'=>$v['goods_id']]);
            $stock = $type == 1?$info['stock'] + $v['number']:$info['stock'] - $v['number'];
            $res = $this->table->update('depot_stock',['depot_id'=>$v['depot_id'],'goods_id'=>$v['goods_id']],['stock' =>$stock]);
            if(!$res){
                return false;
            }
        }
        return true;
    }

}


